package com.hainatong.shiphelper.module.warehouse.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.hainatong.shiphelper.GlobalConfig;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentBrokenSubmitBinding;
import com.hainatong.shiphelper.module.warehouse.SupplierActivity;
import com.hainatong.shiphelper.module.warehouse.entity.BrokenParamBean;
import com.hainatong.shiphelper.module.warehouse.entity.ImpaBean;
import com.hainatong.shiphelper.module.warehouse.entity.SupplierBean;
import com.hainatong.shiphelper.module.warehouse.viewmodel.BrokenViewModel;
import com.hainatong.shiphelper.pictureselector.PictureBean;
import com.hainatong.shiphelper.pictureselector.PictureSelector;
import com.hainatong.shiphelper.utils.FileUtils;
import com.hainatong.shiphelper.utils.PushToast;
import com.hainatong.shiphelper.widget.LoadingDialog;
import com.hainatong.shiphelper.widget.PickerDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//提交 报损
public class BrokenSubmitFragment extends MvvmLazyFragment<FragmentBrokenSubmitBinding, BrokenViewModel>
{
    private static String BROKEN_SUB_TAG = "BrokenSubmitFragment";
    // 报损 物资 code
    private String mImpaCode ;

    private ImpaBean brokenImpa;

    private LoadingDialog loading;

    private BrokenParamBean brokenParam;

    private PickerDialog pickerDialog;

    private List<String> typeList = new ArrayList<>();

    private int seletImgTag = -1;

    private List<String> upLoadImgs;

    public static BrokenSubmitFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( BROKEN_SUB_TAG , scanCode );
        BrokenSubmitFragment brokenFragment = new BrokenSubmitFragment();
        brokenFragment.setArguments( bundle );
        return brokenFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_broken_submit;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
            mImpaCode = args.getString(BROKEN_SUB_TAG , "");
        }
    }

    @Override
    protected void initView(View view)
    {
        loading = new LoadingDialog( getActivity(), getString( R.string.loading ) );
        brokenParam = new BrokenParamBean();
        upLoadImgs = new ArrayList<>();
        //4损坏,5消耗,6报废
        typeList.add("损坏");
        typeList.add("消耗");
        typeList.add("报废");
        // 选 提交 破损 类型
        pickerDialog = new PickerDialog(getActivity(), (selectStr, position) -> {
            //类型
            switch (position)
            {
                case 0:
                    brokenParam.setType("4");
                    break;
                case 1:
                    brokenParam.setType("5");
                    break;
                case 2:
                    brokenParam.setType("6");
                    break;
            }

            viewDataBinding.tvSubType.setText( selectStr );
            ToastUtils.showShort( selectStr );
        });
        // 供应商
        viewDataBinding.rlSupplierBtn.setOnClickListener( v -> {
            //ToastUtils.showShort( "供应商" );
            //viewModel.querySupplier();
            SupplierActivity.start(getActivity());
        } );
        // 选择 提交 类型
        viewDataBinding.btnTypeSelect.setOnClickListener( v -> {

            pickerDialog.showPickContent( typeList );
        } );

        // 选图片 1
        viewDataBinding.ivPhoto1.setOnClickListener( v -> {
            seletImgTag = 1;
            //选择图片
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE)
                    .selectPicture(false);

        } );
        viewDataBinding.ivPhoto2.setOnClickListener( v -> {
            seletImgTag = 2;
            //选择图片
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE)
                    .selectPicture(false);

        } );
        viewDataBinding.ivPhoto3.setOnClickListener( v -> {
            seletImgTag = 3;
            //选择图片
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE)
                    .selectPicture(false);

        } );

        // 破损 提交
        viewDataBinding.btnSubmit.setOnClickListener( v -> {
            // 说明
            String countStr = viewDataBinding.etCountSum.getText().toString();
            if( StringUtils.isEmpty( countStr ) )
            {
                ToastUtils.showShort("请输入数量");
                return;
            }
            int count = Integer.parseInt( countStr );
            brokenParam.setCount( count );
            //设置 上传 的 图片
            if( !upLoadImgs.isEmpty() )
            {
                brokenParam.setFileIdList( upLoadImgs );
            }

            String remarkStr = viewDataBinding.etBrokenInfo.getText().toString();
            brokenParam.setRemark( remarkStr );

            loading.show();
            viewModel.submitBrokenParam( brokenParam );

        } );

        LiveEventBus.get(SupplierActivity.SUPPLIER_RESULT, SupplierBean.class)
                    .observeSticky(this,suppliser -> {
                        viewDataBinding.tvSupplierName.setText( suppliser.getSupplier_name() );

                        brokenParam.setSupplier( suppliser.getSupplier_name() );
                        brokenParam.setSupplier_id( suppliser.getUuid() );
                    });

    }

    @Override
    protected void lazyLoad()
    {
        //首先 先查 物资 信息
        if( !StringUtils.isEmpty( mImpaCode ))
        {
            loading.show();
            viewModel.queryImpaByCode( mImpaCode );
        }

        //拿到 物资信息 后
        viewModel.getImpaResult().observe(this , result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                brokenImpa = result.getData();

                // 设置 物资名称等
                //brokenParam.setImpa_code( brokenImpa.getCode() );
                //brokenParam.setImpa_id( brokenImpa.getUuid() );
                //brokenImpa.getUuid()
                // Original_uuid 领用 物资时候的 uuid
                brokenParam.setOriginal_uuid( "1778e9ec-ea15-4f5b-9a53-74d80659f1bb" );

                //默认 添加人 为 提交的 用户
                if( ObjectUtils.isNotEmpty(GlobalConfig.getInstance().getUserInfo()) )
                {
                    //brokenParam.setCreateID( GlobalConfig.getInstance().getUserInfo().getUuid() );
                    //brokenParam.setCreator( GlobalConfig.getInstance().getUserInfo().getUserTrueName() );
                }
            }
            else
            {
                ToastUtils.showShort(result.getMsg());
            }
        });

        // 默认 type为 损坏
        viewDataBinding.tvSubType.setText("损坏");
        brokenParam.setType("4");

        //破损 提交
        viewModel.getBrokenResult().observe( this , result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                // 提交成功
                PushToast.getInstance(getActivity()).show(PushToast.SUBMIT_SUCCESS);
                //实际开发中将图片上传到服务器成功后需要删除全部缓存图片（即裁剪后的无用图片）
                FileUtils.deleteAllCacheImage(getActivity());

                getActivity().finish();
            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        } );
        // 上传 图片 结果
        viewModel.getUpImgResult().observe( this ,reult -> {
            loading.hide();
            if( reult.isSuccess() )
            {
               switch ( seletImgTag )
               {
                   case 1:
                       if( upLoadImgs.size() <1 )
                       {
                           upLoadImgs.add( reult.getData().getUuid() );
                       }
                       else
                       {
                           upLoadImgs.set(0,reult.getData().getUuid() );
                       }
                       break;
                   case 2:
                       if( upLoadImgs.size() <2 )
                       {
                           upLoadImgs.add( reult.getData().getUuid() );
                       }
                       else
                       {
                           upLoadImgs.set(1,reult.getData().getUuid() );
                       }
                       break;
                   case 3:
                       if( upLoadImgs.size() <3 )
                       {
                           upLoadImgs.add( reult.getData().getUuid() );
                       }
                       else
                       {
                           upLoadImgs.set(2,reult.getData().getUuid() );
                       }
                       break;
               }

            }
            else
            {
                LogUtils.e( reult.getMsg() );
            }
        } );

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        /* 选择图片 结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE)
        {
            if (data != null)
            {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                LogUtils.e("PictureSelector","是否裁剪: " + pictureBean.isCut());
                LogUtils.e("PictureSelector","原图地址: " + pictureBean.getPath());
                LogUtils.e("PictureSelector","图片 Uri: " + pictureBean.getUri());

                File imgFile = new File( pictureBean.getPath() );
                switch ( seletImgTag )
                {
                    case 1:
                        //使用 Glide 加载图片
                        Glide.with(this)
                                .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                                .apply(RequestOptions.centerCropTransform()).into(viewDataBinding.ivPhoto1);
                        viewDataBinding.llImg2.setVisibility(View.VISIBLE);
                        break;
                    case 2:

                        Glide.with(this)
                                .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                                .apply(RequestOptions.centerCropTransform()).into(viewDataBinding.ivPhoto2);
                        viewDataBinding.llImg3.setVisibility(View.VISIBLE);
                        break;
                    case 3:

                        Glide.with(this)
                                .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                                .apply(RequestOptions.centerCropTransform()).into(viewDataBinding.ivPhoto3);
                        break;
                }

                // 发请求 上传图片
                loading.show();
                viewModel.upLoadImg( imgFile );


                if (false)
                {
                    //BitmapFactory.decodeFile(pictureBean.getPath())

                    //图片文件
                    //File file = new File(pictureBean.getPath());

                }
                else
                {
                    //HeadImg.setImageURI(pictureBean.getUri());
                }

            }
        }
    }


    @Override
    public void onDestroy()
    {
        super.onDestroy();
        loading.dismiss();
    }
}
